<?php
// FILE: api/kirim_panggilan.php
header('Content-Type: application/json');
session_start();
require_once '../config/database.php'; 

// --- KONFIGURASI ---
// Pastikan file json ini ada di folder yang sama
define('CREDENTIALS_PATH', __DIR__ . '/fcm-key.json'); 
// -------------------

// 1. Cek Login
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Anda harus login']);
    exit;
}

$target_user_id = $_POST['target_id'] ?? '';
$my_name = $_SESSION['username'] ?? 'Admin';

// 2. Ambil Token HP dari Database
$stmt = $conn->prepare("SELECT fcm_token FROM users WHERE id = ?");
$stmt->bind_param("i", $target_user_id);
$stmt->execute();
$res = $stmt->get_result();
$token = ($res->num_rows > 0) ? $res->fetch_assoc()['fcm_token'] : null;

if ($token) {
    try {
        // A. Ambil Access Token (Login otomatis pakai file JSON)
        $accessToken = getAccessToken(CREDENTIALS_PATH);
        
        // B. Kirim Pesan pakai HTTP v1
        $success = kirimFCMv1($token, $accessToken, $my_name);
        
        if ($success) {
            echo json_encode(['status' => 'success', 'message' => 'Alarm berbunyi!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal kirim ke Google']);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Token tidak ditemukan']);
}

// ==========================================
// FUNGSI UTAMA: HTTP v1 SEND
// ==========================================
function kirimFCMv1($token, $accessToken, $callerName) {
    // Baca Project ID dari file JSON
    $keyData = json_decode(file_get_contents(CREDENTIALS_PATH), true);
    $projectId = $keyData['project_id'];
    
    $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";
    
    // Payload HTTP v1 (Struktur berbeda dengan Legacy)
    // Perhatikan: "message" adalah pembungkus utama
    $payload = [
        "message" => [
            "token" => $token,
            "android" => [
                "priority" => "HIGH" // Wajib agar HP bangun
            ],
            // Data yang akan dibaca MyFirebaseMessagingService.kt
            "data" => [
                "type" => "CALL_ALARM",
                "caller" => $callerName,
                "command" => "RING_ALARM"
            ]
        ]
    ];

    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ($httpCode == 200);
}

// ==========================================
// FUNGSI RAHASIA: OAUTH2 TANPA LIBRARY
// (Membuat Token JWT dari File JSON)
// ==========================================
function getAccessToken($keyPath) {
    if (!file_exists($keyPath)) throw new Exception("File fcm-key.json tidak ditemukan!");
    
    $key = json_decode(file_get_contents($keyPath), true);
    
    // Header JWT
    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $header_base64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

    // Claim Set
    $now = time();
    $claim = json_encode([
        'iss' => $key['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => $now + 3600,
        'iat' => $now
    ]);
    $claim_base64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($claim));

    // Tanda Tangan Digital
    $signature = '';
    openssl_sign($header_base64 . "." . $claim_base64, $signature, $key['private_key'], 'SHA256');
    $signature_base64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

    $jwt = $header_base64 . "." . $claim_base64 . "." . $signature_base64;

    // Tukar JWT dengan Access Token Google
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode($response, true);
    if (!isset($data['access_token'])) throw new Exception("Gagal otentikasi ke Google: " . ($data['error_description'] ?? 'Unknown error'));

    return $data['access_token'];
}
?>
